﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using Abp.Runtime.Caching;
using AutoMapper.QueryableExtensions;
using FwProject.Authorization.Users;
using FwProject.Car;
using FwProject.Car.Dto;
using FwProject.Core.Car;
using FwProject.Core.Distribution;
using FwProject.Core.Restaurant;
using FwProject.Core.TypeNumber;
using FwProject.Distribution.Dto;
using FwProject.Manager;
using FwProject.Restaurant.Dto;
using FwProject.TypeNumber;
using FwProject.TypeNumber.Dto;
using FwProject.Users;
using Microsoft.EntityFrameworkCore;
using X.PagedList;
using Abp.UI;
using FwProject.PublicService.SqlExec;
using FwProject.Distribution;

namespace FwProject.Restaurant
{
    [AbpAuthorize]
    public class LoadCarAppService : FwProjectAppServiceBase, ILoadCarAppService
    {
        public readonly IRepository<LoadCar, Guid> _repositoryLoadCar;
        public readonly IRepository<DistributionInfo, Guid> _distributionInfoRepository;
        public readonly IRepository<RestaurantInfo, Guid> _restaurantInfoRepository;
        public readonly IRepository<DistributionInfoDetails, Guid> _distributionInfoDetailsRepository;
        public readonly IRepository<CarInfo, Guid> _repositoryCarInfo;
        public readonly IRepository<LoadingCarInfo, Guid> _repositoryLoadingCarInfo;
        private readonly IRepository<User, long> _repositoryUser;
        private readonly DistributionInfoManager _distributionManager;
        private readonly LoadCarManager _loadcarManager;
        private readonly LoadingCarManager _loadingCarManager;
        public readonly ILoadingCarAppService _iLoadingCarAppService;
        public readonly ICacheManager _catchmanager;
        private readonly UserManager _userManager;
        public readonly ICarInfoAppService _iCarInfoAppService;
        private readonly IRestaurantTypeNumberAppService _RestaurantTypeNumberAppService;
        private readonly ITypeNumberInfoAppService _ITypeNumberInfoAppService;
        private readonly IUserAppService _IUserAppService;
        private readonly ICarInfoAppService _carInfoAppService;

        private readonly IDistributionAppService _distributionAppService;
        public readonly IRepository<TypeNumberInfo, Guid> _repositoryTypeNumberInfo;
        public IGuidGenerator _guid { get; set; }
        public IObjectMapper _map { get; set; }

        private readonly ISqlExecuter _sqlExecuter;

        public LoadCarAppService(
            ICacheManager catchmanager, IRepository<CarInfo, Guid> repositoryCarInfo,
            IRepository<LoadCar, Guid> repositoryLoadCar, ILoadingCarAppService iLoadingCarAppService,
            LoadCarManager loadcarManager, UserManager userManager, IRepository<LoadingCarInfo, Guid> repositoryLoadingCarInfo,
            IRepository<DistributionInfoDetails, Guid> distributionInfoDetailsRepository,
            IRepository<DistributionInfo, Guid> distributionInfoRepository,
             IRestaurantTypeNumberAppService RestaurantTypeNumberAppService,
             ITypeNumberInfoAppService ITypeNumberInfoAppService,
             ICarInfoAppService iCarInfoAppService,
             LoadingCarManager loadingCarManager,
             IUserAppService IUserAppService,
             ISqlExecuter sqlExecuter,
             IRepository<TypeNumberInfo, Guid> repositoryTypeNumberInfo,
             ICarInfoAppService carInfoAppService,
             IDistributionAppService distributionAppService,
             IRepository<User, long> repositoryUser,
             IRepository<RestaurantInfo, Guid> restaurantInfoRepository,
             DistributionInfoManager distributionManager
        )
        {
            _distributionManager = distributionManager;
            _restaurantInfoRepository = restaurantInfoRepository;
            _guid = SequentialGuidGenerator.Instance;
            _repositoryTypeNumberInfo = repositoryTypeNumberInfo;
            _distributionInfoDetailsRepository = distributionInfoDetailsRepository;
            _IUserAppService = IUserAppService;
            _loadingCarManager = loadingCarManager;
            _iCarInfoAppService = iCarInfoAppService;
            _ITypeNumberInfoAppService = ITypeNumberInfoAppService;
            _RestaurantTypeNumberAppService = RestaurantTypeNumberAppService;
            _repositoryLoadingCarInfo = repositoryLoadingCarInfo;
            _catchmanager = catchmanager;
            _repositoryCarInfo = repositoryCarInfo;
            _repositoryLoadCar = repositoryLoadCar;
            _iLoadingCarAppService = iLoadingCarAppService;
            _loadcarManager = loadcarManager;
            _userManager = userManager;
            _distributionInfoRepository = distributionInfoRepository;
            _sqlExecuter = sqlExecuter;
            _carInfoAppService = carInfoAppService;
            _distributionAppService = distributionAppService;
            _repositoryUser = repositoryUser;
        }

        /// <summary>
        /// 过期不在使用
        /// </summary>
        /// <param name="inputList"></param>
        /// <returns></returns>
        [Obsolete]
        public async Task EditDistribution(List<EditDistributionInpuDto> inputList)
        {
            await GetCache;
        }
        /// <summary>
        /// 过期不在使用
        /// </summary>
        /// <param name="inputList"></param>
        /// <returns></returns>
        [Obsolete]
        public async Task<List<DistributionDto>> GetDistributionDetails(Guid restaurantId)
        {
            await GetCache;
            return null;
        }
        #region App添加一个装车信息
        public async Task<Guid> Create(LoadCarInputDto input)
        {
            var user = await base.GetCurrentUserAsync();
            var model = _map.Map<LoadCar>(input);
            model.Id = _guid.Create();
            model.FactoryinfoId = user.FactoryinfoId.Value;
            model.CreationTime = input.CreationTime;
            //添加司机Id
            model.DriverUserId = input.DriverUserId == null ? AbpSession.UserId : input.DriverUserId;
            model.LoadingCarInfoList = new List<LoadingCarInfo>();
            foreach (var item in input.LoadingCarInputs)
            {
                LoadingCarInfo t = new LoadingCarInfo();
                t = _map.Map<LoadingCarInfo>(item);
                t.Id = _guid.Create();
                t.LoadCarId = model.Id;
                t.TypeNumberName = _repositoryTypeNumberInfo.Get(t.TypeNumberInfoId.Value)?.Name;
                model.LoadingCarInfoList.Add(t);
            }
            return await _loadcarManager.CreateLoadcar(model, model.DriverUserId.Value);
        }
        #endregion
        #region App修改装车信息
        /// <summary>
        /// 修改装车信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Guid> EditLoadCar(LoadEditCarDto input)
        {
            var types = input.LoadingCarInfoList.Select(o => o.TypeNumberInfoId);
            if (types.Distinct().Count() != types.Count())
                throw new UserFriendlyException(2, "不能添加重复的型号！！！");

            var model = await _repositoryLoadCar.GetAllIncluding(o => o.LoadingCarInfoList).Where(o => o.Id == input.Id).FirstOrDefaultAsync();
            if (model != null)
            {
                foreach (var item in input.LoadingCarInfoList)
                {
                    var m = model.LoadingCarInfoList.Where(o => o.Id == item.Id).FirstOrDefault();
                    if (m != null)
                        m.Countproduct = item.Countproduct;
                }
                var loadingId = model.LoadingCarInfoList.Select(o => o.Id).ToList();//当前系统中存在的装车明细
                var listLoadList = input.LoadingCarInfoList;
                if (input.LoadingCarInfoList.Any())
                {
                    if (loadingId.Count > 0)
                    {
                        var removes = loadingId.Where(o => listLoadList.Any(r => r.Id == o) == false).ToList();
                        if (removes?.Count > 0)//判断是否有修改
                            for (int i = 0; i < removes.Count; i++)//执行删除操作
                                await _repositoryLoadingCarInfo.DeleteAsync(removes[i]);
                    }
                }
                var adds = listLoadList.Where(r => loadingId.Any(o => o == r.Id) == false);
                foreach (var a in adds)
                {
                    LoadingCarInfo info = new LoadingCarInfo() { Id = Guid.NewGuid(), TypeNumberInfoId = a.TypeNumberInfoId, Countproduct = a.Countproduct, LoadCarId = model.Id };
                    await _repositoryLoadingCarInfo.InsertAndGetIdAsync(info);
                }
            }
            model.CarStatus = CarStatus.出库审核中;
            await _loadcarManager.UpdateLoadcar(model);
            return model.Id;
        }
        #endregion
        #region App装车的时候返回不是默认装车型号数据
        /// <summary>
        ///装车时获取不是默认的装车数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<TypeNumberInfoDto>> GetNotDefaultTypeNumber()
        {
            var user = await UserManager.GetUserByIdAsync(AbpSession.UserId.Value);
            var list = (await _ITypeNumberInfoAppService.GetAllSystemTypeNumber()).Where(o => o.FactoryinfoId == user.FactoryinfoId);
            var Examinemodel = (await GetCache).Where(o => o.CarStatus == CarStatus.已装车 && o.DriverUserId == AbpSession.UserId.Value && o.ExamineStatus == ExamineStatus.未审核).FirstOrDefault();
            List<TypeNumberInfoDto> listTypeinfo = new List<TypeNumberInfoDto>();
            if (Examinemodel != null)
            {
                var i = Examinemodel.LoadingCarInfoList.Select(o => o.TypeNumberInfoId).ToList();
                if (i.Count() > 0)
                {
                    listTypeinfo = list.Where(o => i.Any(t => o.Id == t) == false).ToList();

                }
            }
            return listTypeinfo;
        }
        #endregion
        #region App未使用方法
        /// <summary>
        /// 创建一个装车
        /// </summary>
        /// <returns>The create.</returns>
        /// <param name="input">Input.</param>
        public async Task CreateLoadCar(Guid id, LoadCarInputDto input)
        {
            var model = _map.Map<LoadCar>(input);
            model.Id = id;
            model.LoadingCarInfoList = new List<LoadingCarInfo>();
            foreach (var item in input.LoadingCarInputs)
            {
                LoadingCarInfo t = new LoadingCarInfo();
                t = _map.Map<LoadingCarInfo>(item);
                t.Id = _guid.Create();
                t.LoadCarId = model.Id;
                model.LoadingCarInfoList.Add(t);
            }
            await _repositoryLoadCar.InsertAndGetIdAsync(model);
        }
        #endregion
        #region  App车辆装车配送状态修改
        /// <summary>
        /// 装车状态修改
        /// </summary>
        /// <returns>The status.</returns>
        /// <param name="id">Identifier.</param>
        public async Task EditStatus(LoadCarUpdate loadCarInfo)
        {

            var model = await _repositoryLoadCar.GetAsync(loadCarInfo.LoadCarId);
            if (model.CarStatus == loadCarInfo.CarStatus)
                throw new UserFriendlyException("状态已更改");

            model.CarStatus = loadCarInfo.CarStatus;
            if (model.CarStatus == CarStatus.回库审核中)
            {
                model.BackStatusOverTime = DateTime.Now;
            }
            if (model.CarStatus == CarStatus.配送完成)
            {
                model.OverTime = DateTime.Now;
                model.BackUserId = AbpSession.UserId.Value;
                model.BackStatus = BackStatus.已审核;
            }
            await _loadcarManager.UpdateLoadcar(model);
        }
        /// <summary>
        /// 库管审核状态
        /// </summary>
        /// <param name="loadCarInfo"></param>
        /// <returns></returns>
        public async Task EditAndCarLoadIngStatus(List<LoadingCarUpdateInput> loadCarInfo)
        {
            foreach (var item in loadCarInfo)
            {
                var model = await _repositoryLoadCar.GetAsync(item.LoadCarId);
                model.CarStatus = item.CarStatus;
                if (item.CarStatus == CarStatus.配送中)
                {
                    model.OutUserId = AbpSession.UserId.Value;
                    model.ExamineStatus = ExamineStatus.已审核;
                }

                foreach (var itemLoding in item.LoadingModel)
                {
                    var loading = await _repositoryLoadingCarInfo.GetAsync(itemLoding.Id);

                    loading.Countproduct = itemLoding.UpdateCount;

                    await _loadingCarManager.UpdateLoadingcar(loading);

                }
                await _loadcarManager.UpdateLoadcar(model);
            }

        }
        /// <summary>
        /// 后台装车审核
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task UpdateStatus(Guid id, ExamineStatus examine)
        {
            var model = await _repositoryLoadCar.GetAsync(id);

            model.CarStatus = CarStatus.配送中;
            model.OutUserId = AbpSession.UserId.Value;
            model.ExamineStatus = examine;

            await _loadcarManager.UpdateLoadcar(model);
        }
        /// <summary>
        /// 库管退回
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task BackLoadCarStatus(Guid Id)
        {
            var model = await _repositoryLoadCar.GetAsync(Id);
            model.CarStatus = CarStatus.已装车;
            model.ExamineStatus = ExamineStatus.未审核;
            await _loadcarManager.UpdateLoadcar(model);
        }
        #endregion
        #region App获取一个装车信息
        /// <summary>
        /// 获取装车信息
        /// </summary>
        /// <returns>The by identifier async.</returns>
        /// <param name="id">Identifier.</param>
        public async Task<LoadCarDto> GetByIdAsync(Guid id)
        {
            var model = await _repositoryLoadCar.GetAsync(id);
            return _map.Map<LoadCarDto>(model);

        }
        #endregion
        #region App 获取车内详情
        /// <summary>
        /// APP获取车内详情
        /// </summary>
        /// <returns></returns>
        public async Task<CarShopInfo> GetByNowCarInfoAsync()
        {
            CarShopInfo carinfo = new CarShopInfo();
            var user = await base.GetCurrentUserAsync();
            var typeNubers = _repositoryTypeNumberInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);
            var model = (await GetCache).Where(o => o.CarStatus == CarStatus.配送中 && o.DriverUserId == AbpSession.UserId.Value).FirstOrDefault();
            if (model != null)
            {
                var m = _distributionInfoRepository.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => o.LoadCarId == model.Id).SelectMany(s => s.DistributionInfoListDetails);
                //var disIds = m.Select(o => o.Id).ToArray();
                /////得到所有的配送信息
                //var list = await _distributionInfoDetailsRepository.GetAll().Where(o => disIds.Any(s => s == o.DistributionInfoId)).ToListAsync();
                // var li = _map.Map<List<DistributionDetailsDto>>(list);

                var li = _map.Map<List<DistributionDetailsDto>>(m);

                ////// 获取实际配送情况
                var kmodel = await li.GroupBy(o => o.TypeNumberInfoId).Select(o => new LoadIngInfoOutPutDto
                {
                    TypeNumberInfoId = o.Key.Value,
                    RestaurantTypeNumber = o.Select(b => b.TypeNumberInfoModel).FirstOrDefault(),
                    Distributioncount = o.Sum(k => k.Distributioncount),
                    Recoverycount = o.Sum(k => k.Recoverycount),
                    Exchangegoodscount = o.Sum(k => k.Exchangegoodscount),
                    Damagecount = o.Sum(k => k.Damagecount),
                    Givecount = o.Sum(k => k.Givecount),
                    Backboxcount = o.Sum(k => k.Backboxcount),
                    Backnumbercount = o.Sum(k => k.Backnumbercount),
                }).ToListAsync();


                var listMode = await model.LoadingCarInfoList.GroupJoin(kmodel.DefaultIfEmpty(new LoadIngInfoOutPutDto()), t => t.TypeNumberInfoId, k => k.TypeNumberInfoId, (t, k) => new LoadIngInfoOutPutDto
                {
                    TypeNumberInfoId = t.TypeNumberInfoId.Value,
                    RestaurantTypeNumber = k.FirstOrDefault()?.RestaurantTypeNumber ?? _map.Map<TypeNumberInfoDto>(typeNubers.Where(o => o.Id == t.TypeNumberInfoId).ToList().FirstOrDefault()),
                    Distributioncount = k.FirstOrDefault()?.Distributioncount ?? 0,
                    Recoverycount = k.FirstOrDefault()?.Recoverycount ?? 0,
                    Exchangegoodscount = k.FirstOrDefault()?.Exchangegoodscount ?? 0,
                    Damagecount = k.FirstOrDefault()?.Damagecount ?? 0,
                    Givecount = k.FirstOrDefault()?.Givecount ?? 0,
                    Backboxcount = k.FirstOrDefault()?.Backboxcount ?? 0,
                    Backnumbercount = k.FirstOrDefault()?.Backnumbercount ?? 0,
                    LoadCount = t.Countproduct,
                }).ToListAsync();

                carinfo.DistributionCount = m.Count();///配送总商家
                carinfo.LoadCount = model.LoadingCarInfoList.Sum(o => o.Countproduct);//装车总数量
                carinfo.CarInfoModel = _map.Map<CarInfoDto>(model.CarInfoModel);
                carinfo.LoadIngInfoOutPutDto = listMode;
                carinfo.LoadCarId = model.Id;
                carinfo.DrvierName = user.Name;
                carinfo.PlatesNumber = model.CarInfoModel.PlatesNumber;
            }
            return carinfo;
        }
        #endregion

        #region App 判断当前司机是重新装车还是修改装车数据如果是配送中返回配送数据
        /// <summary>
        /// 获取装车信息
        /// </summary>
        /// <returns>The by identifier async.</returns>
        /// <param name="id">Identifier.</param>
        public async Task<Tuple<bool, LoadCarDto, LoadCarDto>> GetLoadCarInfoByAsync()
        {
            ///此接口不够完善没有计算出此装车已经下单过的型号数量依然返回的是装车前的数量 交给前端先用到
            ///你这边来计算该车上每个号的剩余数量
            ///通过装车id和卡车型号 查询配送表 DistributionDetailsAppService
            ///_map.Map LoadCarDto (model).LoadingCarInfo.Countproduct 循环判断总的装车-已经配送过的数据（DistributionDetailsAppService）;

            var model = (await GetCache).Where(o => o.CarStatus == CarStatus.配送中 && o.DriverUserId == AbpSession.UserId.Value).FirstOrDefault();
            if (model != null)
            {
                var listCarinfo = await _repositoryLoadingCarInfo.GetAllIncluding(o => o.TypeNumberInfoModel).Where(O => O.LoadCarId == model.Id).OrderByDescending(m => m.CreationTime).ToListAsync();
                model.LoadingCarInfoList = listCarinfo;
            }
            var Examinemodel = (await GetCache).Where(o => o.CarStatus == CarStatus.已装车 && o.DriverUserId == AbpSession.UserId.Value && o.ExamineStatus == ExamineStatus.未审核).FirstOrDefault();
            bool flag = true;//如果存在不可装车//如果不存在代表修改
            if (Examinemodel != null)
            {
                flag = false;
                var listCarinfo = await _repositoryLoadingCarInfo.GetAllIncluding(o => o.TypeNumberInfoModel).Where(O => O.LoadCarId == Examinemodel.Id).OrderByDescending(m => m.CreationTime).ToListAsync();
                Examinemodel.LoadingCarInfoList = listCarinfo;
            }
            return Tuple.Create(flag, _map.Map<LoadCarDto>(model), _map.Map<LoadCarDto>(Examinemodel));

        }
        #endregion
        #region App 返回当前司机装车列表
        /// <summary>
        /// 返回装车列表
        /// </summary>
        /// <returns>The restaurant paged list async.</returns>
        /// <param name="">Page index.</param>
        public async Task<X.PagedList.IPagedList<LoadCarDto>> GetPagedListAsync(int pageIdx, int pageSize, DateTime? begindateTime, DateTime? enddatetime)
        {
            var user = await _userManager.FindByIdAsync(AbpSession.UserId.Value.ToString());
            var query = (await GetCache).Where(o => o.DriverUserId == AbpSession.UserId.Value).OrderByDescending(m => m.CreationTime).AsQueryable();
            if (begindateTime != null)
                query = query.Where(o => o.CreationTime >= begindateTime);

            if (enddatetime != null)
                query = query.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));

            foreach (var item in query)
            {
                var listCarinfo = await _repositoryLoadingCarInfo.GetAllIncluding(o => o.TypeNumberInfoModel).Where(O => O.LoadCarId == item.Id).ToListAsync();
                item.LoadingCarInfoList = listCarinfo;
            }

            return await query.ProjectTo<LoadCarDto>().ToPagedListAsync(pageIdx, pageSize);

        }
        #endregion
        #region App库管盘点接口
        /// <summary>
        /// 库管盘点接口
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="pageSize"></param>
        /// <param name="carStatus"></param>
        /// <param name="begindateTime"></param>
        /// <param name="enddatetime"></param>
        /// <returns></returns>
        public async Task<List<CarShopInfo>> GetLoadCarPagedListAsync(int pageIdx, int pageSize, CarStatus carStatus, DateTime? begindateTime, DateTime? enddatetime)
        {

            var user = await base.GetCurrentUserAsync();
            var typeNubers = _repositoryTypeNumberInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);
            ///获取所司机
            long[] userList = await _iCarInfoAppService.GetCarUserIdList();
            List<CarShopInfo> Carlist = new List<CarShopInfo>();
            var query = (await GetCache).AsQueryable();
            if (begindateTime != null)
                query = query.Where(o => o.CreationTime >= begindateTime.Value);

            if (enddatetime != null)
                query = query.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));
            ///根据状态查询所有的装车信息


            var collection = query.Where(o => o.CarStatus == carStatus && o.FactoryinfoId == user.FactoryinfoId).OrderByDescending(o => o.Id).ToPagedList(pageIdx, pageSize);
            foreach (var kitem in collection)
            {

                CarShopInfo carinfo = new CarShopInfo();
                carinfo.CreationTime = kitem.CreationTime;
                carinfo.CarStatus = kitem.CarStatus;
                carinfo.DrvierName = (await _IUserAppService.GetByIdUserAsync(kitem.DriverUserId.Value)).Name;
                carinfo.PlatesNumber = (await _iCarInfoAppService.GetByIdAsync(kitem.DriverUserId.Value)).PlatesNumber;

                var t = _distributionInfoRepository.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => o.LoadCarId == kitem.Id);
                List<DistributionInfoDetails> list = new List<DistributionInfoDetails>();
                foreach (var item in t)
                {
                    list.AddRange(item.DistributionInfoListDetails);
                }
                var li = _map.Map<List<DistributionDetailsDto>>(list);

                ////// 获取实际配送情况
                var kmodel = await li.GroupBy(o => o.TypeNumberInfoId).Select(o => new LoadIngInfoOutPutDto
                {
                    TypeNumberInfoId = o.Key.Value,
                    RestaurantTypeNumber = o.Select(b => b.TypeNumberInfoModel).FirstOrDefault(),
                    Distributioncount = o.Sum(k => k.Distributioncount),
                    Recoverycount = o.Sum(k => k.Recoverycount),
                    Exchangegoodscount = o.Sum(k => k.Exchangegoodscount),
                    Damagecount = o.Sum(k => k.Damagecount),
                    Givecount = o.Sum(k => k.Givecount),
                    Backboxcount = o.Sum(k => k.Backboxcount),
                    Backnumbercount = o.Sum(k => k.Backnumbercount)
                }).ToListAsync();

                var listMode = await kitem.LoadingCarInfoList.GroupJoin(kmodel.DefaultIfEmpty(new LoadIngInfoOutPutDto()), m => m.TypeNumberInfoId, k => k.TypeNumberInfoId, (m, k) => new LoadIngInfoOutPutDto
                {
                    TypeNumberInfoId = m.TypeNumberInfoId.Value,
                    RestaurantTypeNumber = k.FirstOrDefault()?.RestaurantTypeNumber ?? _map.Map<TypeNumberInfoDto>(typeNubers.Where(o => o.Id == m.TypeNumberInfoId).ToList().FirstOrDefault()),
                    Distributioncount = k.FirstOrDefault()?.Distributioncount ?? 0,
                    Recoverycount = k.FirstOrDefault()?.Recoverycount ?? 0,
                    Exchangegoodscount = k.FirstOrDefault()?.Exchangegoodscount ?? 0,
                    Damagecount = k.FirstOrDefault()?.Damagecount ?? 0,
                    Givecount = k.FirstOrDefault()?.Givecount ?? 0,
                    Backboxcount = k.FirstOrDefault()?.Backboxcount ?? 0,
                    Backnumbercount = k.FirstOrDefault()?.Backnumbercount ?? 0,
                    LoadCount = m.Countproduct,
                }).ToListAsync();


                carinfo.DistributionCount = t.Count();///配送总商家
                carinfo.LoadCount = kitem.LoadingCarInfoList.Sum(o => o.Countproduct);//装车总数量
                carinfo.CarInfoModel = _map.Map<CarInfoDto>(kitem.CarInfoModel);
                carinfo.CreationTime = kitem.BackStatusOverTime.Value;
                carinfo.LoadIngInfoOutPutDto = listMode;
                carinfo.LoadCarId = kitem.Id;
                Carlist.Add(carinfo);
            }
            return Carlist;
        }

        /// <summary>
        /// 库管盘点接口
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="pageSize"></param>
        /// <param name="carStatus"></param>
        /// <param name="begindateTime"></param>
        /// <param name="enddatetime"></param>
        /// <returns></returns>
        public async Task<List<CarShopInfo>> GetLoadCarAllInfoPagedListAsync(int pageIdx, int pageSize, long? carUserId, CarStatus? carStatus, DateTime? begindateTime, DateTime? enddatetime, int orderBy = 0)
        {

            var user = await base.GetCurrentUserAsync();
            var typeNubers = _repositoryTypeNumberInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);
            ///获取所司机
            long[] userList = await _iCarInfoAppService.GetCarUserIdList();
            List<CarShopInfo> Carlist = new List<CarShopInfo>();
            var query = (await GetCache).AsQueryable().Where(o => o.FactoryinfoId == user.FactoryinfoId);

            if (carUserId != null)
                query = query.Where(o => o.DriverUserId == carUserId.Value);

            if (begindateTime != null)
                query = query.Where(o => o.BackStatusOverTime >= begindateTime);

            if (enddatetime != null)
                query = query.Where(o => o.BackStatusOverTime <= enddatetime.Value.AddHours(24));
            ///根据状态查询所有的装车信息
            if (carStatus != null)
                query = query.Where(o => o.CarStatus == carStatus.Value);

            var collection = query.OrderByDescending(o => o.CreationTime).ToPagedList(pageIdx, pageSize);

            foreach (var kitem in collection)
            {

                CarShopInfo carinfo = new CarShopInfo();
                carinfo.CreationTime = kitem.CreationTime;
                carinfo.CarStatus = kitem.CarStatus;
                carinfo.DrvierName = (await _IUserAppService.GetByIdUserAsync(kitem.DriverUserId.Value)).Name;
                carinfo.PlatesNumber = (await _iCarInfoAppService.GetByIdAsync(kitem.DriverUserId.Value)).PlatesNumber;

                var t = _distributionInfoRepository.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => o.LoadCarId == kitem.Id);
                List<DistributionInfoDetails> list = new List<DistributionInfoDetails>();
                foreach (var item in t)
                {
                    list.AddRange(item.DistributionInfoListDetails);
                }
                var li = _map.Map<List<DistributionDetailsDto>>(list);

                ////// 获取实际配送情况
                var kmodel = await li.GroupBy(o => o.TypeNumberInfoId).Select(o => new LoadIngInfoOutPutDto
                {
                    TypeNumberInfoId = o.Key.Value,
                    Distributioncount = o.Sum(k => k.Distributioncount),
                    Recoverycount = o.Sum(k => k.Recoverycount),
                    Exchangegoodscount = o.Sum(k => k.Exchangegoodscount),
                    Damagecount = o.Sum(k => k.Damagecount),
                    Givecount = o.Sum(k => k.Givecount),
                    Backboxcount = o.Sum(k => k.Backboxcount),
                    Backnumbercount = o.Sum(k => k.Backnumbercount)
                }).ToListAsync();

                var listMode = await kitem.LoadingCarInfoList.GroupJoin(kmodel.DefaultIfEmpty(new LoadIngInfoOutPutDto()), m => m.TypeNumberInfoId, k => k.TypeNumberInfoId, (m, k) => new LoadIngInfoOutPutDto
                {
                    TypeNumberInfoId = m.TypeNumberInfoId.Value,
                    RestaurantTypeNumber = _map.Map<TypeNumberInfoDto>(typeNubers.Where(o => o.Id == m.TypeNumberInfoId).ToList().FirstOrDefault()),
                    Distributioncount = k.FirstOrDefault()?.Distributioncount ?? 0,
                    Recoverycount = k.FirstOrDefault()?.Recoverycount ?? 0,
                    Exchangegoodscount = k.FirstOrDefault()?.Exchangegoodscount ?? 0,
                    Damagecount = k.FirstOrDefault()?.Damagecount ?? 0,
                    Givecount = k.FirstOrDefault()?.Givecount ?? 0,
                    Backboxcount = k.FirstOrDefault()?.Backboxcount ?? 0,
                    Backnumbercount = k.FirstOrDefault()?.Backnumbercount ?? 0,
                    LoadCount = m.Countproduct,
                }).ToListAsync();


                carinfo.DistributionCount = t.Count();///配送总商家
                carinfo.LoadCount = kitem.LoadingCarInfoList.Sum(o => o.Countproduct);//装车总数量
                carinfo.CarInfoModel = _map.Map<CarInfoDto>(kitem.CarInfoModel);
                carinfo.LoadIngInfoOutPutDto = listMode;
                carinfo.LoadCarId = kitem.Id;
                Carlist.Add(carinfo);
            }
            return Carlist;
        }
        #endregion
        #region 库管出库审核
        /// <summary>
        ///获取待审核的装车信息
        /// </summary>
        /// <returns></returns>
        public async Task<X.PagedList.IPagedList<LoadCarDto>> GetPagedStatusListAsync(int pageIdx, int pageSize)
        {


            var user = await _userManager.FindByIdAsync(AbpSession.UserId.Value.ToString());
            var query = (await _repositoryLoadCar.GetAllIncluding(o => o.LoadingCarInfoList).ToListAsync()).Where(o => o.DriverUserId == AbpSession.UserId.Value && o.CarStatus == CarStatus.出库审核中).OrderByDescending(m => m.CreationTime).AsQueryable();

            return await query.ProjectTo<LoadCarDto>().ToPagedListAsync(pageIdx, pageSize);
        }
        /// <summary>
        /// 初次审核
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="pageSize"></param>
        /// <param name="carStatus"></param>
        /// <param name="begindateTime"></param>
        /// <param name="enddatetime"></param>
        /// <returns></returns>
        public async Task<IPagedList<LoadCarDto>> GetByOneLoadCarPagedListAsync(int pageIdx, int pageSize, DateTime? begindateTime, DateTime? enddatetime)
        {
            var user = await base.GetCurrentUserAsync();

            long[] userList = await _iCarInfoAppService.GetCarUserIdList();

            var query = _repositoryLoadCar.GetAllIncluding(o => o.LoadingCarInfoList);
            if (begindateTime != null)
                query = query.Where(o => o.CreationTime >= begindateTime.Value);

            if (enddatetime != null)
                query = query.Where(o => o.CreationTime <= enddatetime.Value.AddHours(24));

            var collection = query.Where(o => o.CarStatus == CarStatus.出库审核中 && o.FactoryinfoId == user.FactoryinfoId).OrderByDescending(m => m.CreationTime).ProjectTo<LoadCarDto>().ToPagedList(pageIdx, pageSize);

            foreach (var kitem in collection)
            {
                foreach (var item in kitem.LoadingCarInfoList)
                {
                    item.TypeNumberInfoModel = (await _ITypeNumberInfoAppService.GetByIdAsync(item.TypeNumberInfoId));
                }
                ////// 获取实际配送情况

            }
            return collection;
        }

        #endregion
        #region 后台方法
        /// <summary>
        /// 添加或者修改新型号数据
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateType(Guid id, LoadCarTypesEnterDto input)
        {
            var model = await _repositoryLoadCar.GetAsync(id);

            var m = _distributionInfoRepository.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => o.LoadCarId == id).SelectMany(s => s.DistributionInfoListDetails).GroupBy(g => g.TypeNumberInfoId).Select(s => s.Key.Value);
            //获取所有不为0的装车数据
            var newloadcars = input.LoadCarTypeDetails.Where(o => o.LoadCarCount > 0 || m.Any(s => s == o.TypeNumberInfoId)).ToList();
            //根据装车Id获取原装车型号
            var original = _repositoryLoadingCarInfo.GetAll().Where(o => o.LoadCarId == id);


            //没有修改的装车信息
            var modify = original.Where(o => newloadcars.Any(s => s.TypeNumberInfoId == o.TypeNumberInfoId)).ToList();
            foreach (var item in modify)
            {
                //比对拿到修改的装车信息
                var n = newloadcars.Where(o => o.TypeNumberInfoId == item.TypeNumberInfoId).FirstOrDefault();
                if (n != null)
                {
                    item.Countproduct = n.LoadCarCount;//修改装车套数
                }
            }


            //对比获取要删除的装车型号
            var removes = original.Where(o => newloadcars.Any(s => s.TypeNumberInfoId == o.TypeNumberInfoId) == false).ToList();
            //执行删除
            if (removes?.Count > 0)
            {                                                 
                for (int i = 0; i < removes.Count; i++)
                {
                    await _repositoryLoadingCarInfo.DeleteAsync(removes[i]);
                }
            }

            //通过对比获取新增的装车信息
            var adds = newloadcars.Where(o => original.Any(s => s.TypeNumberInfoId == o.TypeNumberInfoId) == false).ToList();
            foreach (var item in adds)
            {
                LoadingCarInfo entity = new LoadingCarInfo
                {
                    Id = _guid.Create(),
                    Countproduct = item.LoadCarCount,
                    TypeNumberInfoId = item.TypeNumberInfoId,
                    TypeNumberName=item.TypeNumberName,
                    LoadCarId = id
                };

                await _repositoryLoadingCarInfo.InsertAsync(entity);
            }

          



        }
        /// <summary>
        /// 根据装车id查看装车信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<LoadCarOutputDto> GetLoadCarInfo(Guid id)
        {
            var user = await UserManager.GetUserByIdAsync(AbpSession.UserId.Value);
            var model = _repositoryLoadCar.GetAllIncluding(o => o.LoadingCarInfoList).Where(o => o.Id == id).FirstOrDefault();
            var loadcar = _map.Map<LoadCarOutputDto>(model);
            var typeNumber = _repositoryTypeNumberInfo.GetAll().Where(o => o.FactoryinfoId == user.FactoryinfoId);

            loadcar.LoadingCarInfoList = typeNumber.GroupJoin(model.LoadingCarInfoList, t => t.Id, k => k.TypeNumberInfoId, (o, i) =>
             new LoadingCarDto
             {
                 LoadCarId = model.Id,
                 TypeNumberInfoId = o.Id,
                 TypeNumberInfoModel = _map.Map<TypeNumberInfoDto>(o),
                 Countproduct = i.Select(b => b.Countproduct).FirstOrDefault(),
                 Id = i.Select(b => b.Id).FirstOrDefault()

             }).ToList();
            return loadcar;
        }
        /// <summary>
        /// 修改装车信息
        /// </summary>
        /// <returns>The update.</returns>
        /// <param name="id">Identifier.</param>
        /// <param name="input">Input.</param>
        public async Task Update(Guid id, LoadCarInputDto input)
        {
            var model = await _repositoryLoadCar.GetAsync(id);
            model = _map.Map(input, model);
            await _loadcarManager.UpdateLoadcar(model);

        }

        /// <summary>
        /// 临时配送
        /// </summary>
        /// <param name="input"></param>
        /// <param name="driverId"></param>
        /// <returns></returns>
        public async Task CreateLoadCarAndDistribution(DistributionInpuDto input, long driverId)
        {
            var user = (await GetCurrentUserAsync());
            var types = input.DetailsInputDtos.Select(o => o.TypeNumberInfoId);
            if (types.Distinct().Count() != types.Count())
                throw new UserFriendlyException(2, "请合并重复的型号！！！");
            if (input.DetailsInputDtos.Sum(o => o.Distributioncount + o.Backboxcount + o.Exchangegoodscount + o.Givecount + o.Damagecount + o.Recoverycount + o.Backnumbercount) == 0)
            {
                throw new UserFriendlyException("请输入配送箱数！");
            }
            var car = await _carInfoAppService.GetByIdAsync(driverId);
            if (car == null)
                throw new UserFriendlyException(200,"该司机没有绑定车辆！");
            ///临时装车信息
            LoadCarInputDto loadinput = new LoadCarInputDto()
            {
                Carinfoid = car.Id,
                CarStatus = CarStatus.配送完成,
                ExamineStatus = ExamineStatus.已审核,
                BackStatus = BackStatus.已审核,
                LoadingCarInputs = new List<LoadingCarInputDto>(),
                BackUserId = AbpSession.UserId.Value,
                OutUserId = AbpSession.UserId.Value,
                DriverUserId = driverId,
                CreatorUserId = driverId,
                CreationTime = input.CreationTime
            };
            foreach (var item in input.DetailsInputDtos)
            {
                LoadingCarInputDto dto = new LoadingCarInputDto();
                dto.TypeNumberInfoId = item.TypeNumberInfoId.Value;
                dto.TypeNumberName = item.TypeNumberName;
                dto.Countproduct = item.Distributioncount;
                loadinput.LoadingCarInputs.Add(dto);
            }
            var model = _map.Map<LoadCar>(loadinput);
            model.Id = _guid.Create();
            model.OverTime = DateTime.Now;
            model.BackStatusOverTime = DateTime.Now;
            model.FactoryinfoId = user.FactoryinfoId.Value;
            model.CreationTime = input.CreationTime;
            model.LoadingCarInfoList = new List<LoadingCarInfo>();
            foreach (var item in loadinput.LoadingCarInputs)
            {
                LoadingCarInfo t = new LoadingCarInfo();
                t = _map.Map<LoadingCarInfo>(item);
                t.Id = _guid.Create();
                t.LoadCarId = model.Id;
                t.CreatorUserId = driverId;
                t.CreationTime = input.CreationTime;
                model.LoadingCarInfoList.Add(t);
            }
            await _repositoryLoadCar.InsertAndGetIdAsync(model);

            DistributionInpuDto distributionInpuDto = new DistributionInpuDto()
            {
                Carinfoid = car.Id,
                LoadCarId = model.Id,
                CreatorUserId = driverId,
                Pricestatus = Pricestatus.未结账,
                Restaurantid = input.Restaurantid,
                TotalPrice = input.TotalPrice,
                Stock = input.Stock,
                DistributionStock = input.DistributionStock,
                CreationTime = input.CreationTime,
                DetailsInputDtos = new List<DistributionDetailsInputDto>()
            };
            //foreach (var item in input.DetailsInputDtos)
            //{
            //    DistributionDetailsInputDto dto = new DistributionDetailsInputDto()
            //    {
            //        TypeNumberInfoId = item.TypeNumberInfoId,
            //        TypeNumberName = item.TypeNumberName,
            //        RestaurantTypenNumberInfoId = item.RestaurantTypenNumberInfoId,
            //        Restaurantid = item.Restaurantid,
            //        Distributioncount = item.Distributioncount,
            //        Recoverycount = item.Distributioncount,
            //        Givecount = item.Givecount,
            //        Exchangegoodscount = item.Exchangegoodscount,
            //        Damagecount = item.Damagecount,
            //        Backboxcount = item.Backboxcount,
            //        Backnumbercount = item.Backnumbercount,
            //        Pricestatus = Pricestatus.未结账,
            //        TypeNumberPrice = item.TypeNumberPrice,
            //        Sumprice = item.Sumprice
            //    };
            //    distributionInpuDto.DetailsInputDtos.Add(dto);
            //}
            ///配送数据
            distributionInpuDto.DetailsInputDtos = input.DetailsInputDtos;
            var rmodel = _restaurantInfoRepository.Get(distributionInpuDto.Restaurantid);
            if (distributionInpuDto.Stock != rmodel.RealStock)
                rmodel.RealStock = distributionInpuDto.Stock;

            var dismodel = _map.Map<DistributionInfo>(distributionInpuDto);
            dismodel.Id = _guid.Create();
            dismodel.FactoryinfoId = user.FactoryinfoId;
            //dismodel.DistributionStock = //rmodel.RealStock + input.DetailsInputDtos.Sum(s => s.Distributioncount + s.Givecount - s.Backboxcount - s.Recoverycount);
            //rmodel.RealStock = input.Stock;

            dismodel.DistributionInfoListDetails = new List<DistributionInfoDetails>();
            foreach (var item in distributionInpuDto.DetailsInputDtos)
            {
                DistributionInfoDetails t = new DistributionInfoDetails();
                t = _map.Map<DistributionInfoDetails>(item);
                t.Id = _guid.Create();
                t.CreatorUserId = distributionInpuDto.CreatorUserId;
                t.DistributionInfoId = dismodel.Id;
                t.CreationTime = input.CreationTime;
                var typeModel = _repositoryTypeNumberInfo.Get(item.TypeNumberInfoId.Value);
                t.TypeNumberName = typeModel.Name;
                ///当自身默认绑定了该型号
                if (item.RestaurantTypenNumberInfoId != null && item.RestaurantTypenNumberInfoId != Guid.Empty)
                {
                    var itemRestaurantTypenNumber = (await (_RestaurantTypeNumberAppService.GetByIdAsync(item.RestaurantTypenNumberInfoId.Value)));
                    t.TypeNumberPrice = itemRestaurantTypenNumber.Price;
                }
                else
                {
                    t.TypeNumberPrice = item.TypeNumberPrice;
                }
                t.Sumprice = t.TypeNumberPrice * ((t.Distributioncount - t.Backboxcount) * typeModel.Count - t.Backnumbercount - t.Damagecount);
                // t.TypeNumberInfoId = (await (_RestaurantTypeNumberAppService.GetByIdAsync(t.RestaurantTypenNumberInfoId.Value))).TypeNumberId;
                //明细计算
                dismodel.DistributionInfoListDetails.Add(t);


            }
            //金额计算
            dismodel.TotalPrice = dismodel.DistributionInfoListDetails.Sum(o => o.Sumprice);
            await _distributionManager.CreateDistribution(dismodel);

            //  await _distributionAppService.Create(distributionInpuDto);
        }


        public async Task<IPagedList<LoadCarOutputDto>> GetAllLoadingInvoiceAsync(int pageIdx, int pageSize, LoadInvoiceFilter filter = null)
        {
            var user = await _userManager.FindByIdAsync(AbpSession.UserId.Value.ToString());

            var query = (await GetCache).AsQueryable().Where(o => o.FactoryinfoId == user.FactoryinfoId);
            if (filter != null)
            {

                //创建时间开始时间
                if (filter.BeginLimit.HasValue)
                    query = query.Where(o => o.CreationTime >= filter.BeginLimit);

                //创建时间结束时间
                if (filter.EndLimit.HasValue)
                    query = query.Where(o => o.CreationTime <= filter.EndLimit.Value.AddHours(24));


                if (filter.ExamineStatus.HasValue)//审核状态
                    query = query.Where(o => o.ExamineStatus == filter.ExamineStatus.Value);

                if (filter.DriverId.HasValue)//司机
                    query = query.Where(o => o.CarInfoModel.EmployeeCarUserId == filter.DriverId.Value);

                if (!string.IsNullOrWhiteSpace(filter.PlatesNumber))//车牌号
                    query = query.Where(o => o.CarInfoModel.PlatesNumber.Contains(filter.PlatesNumber));
            }
            var data = await query.OrderByDescending(m => m.CreationTime).ProjectTo<LoadCarOutputDto>().ToPagedListAsync(pageIdx, pageSize);

            foreach (var item in data)
            {
                var delis = _distributionInfoRepository.GetAll().Where(o => o.LoadCarId == item.Id).Count();
                item.DeliveredCount = delis;

                item.DriverName = (await _userManager.FindByIdAsync(item.CarInfoModel.EmployeeCarUserId.ToString())).Name;
            }

            return data;
        }

        public async Task<List<LoadCarExportDto>> GetLoadingInvoiceListAsync(LoadInvoiceFilter filter = null)
        {
            #region sql
            //string sql = $@"select distinct CreationNumber,ExamineStatus,a.CreationTime,a.DriverUserId as DriverUserId,d.Name as DriverName,PlatesNumber,CarStatus,e.Name as TypeNumberName,Countproduct,Unit from LoadCar a,LoadingCarInfo b,CarInfo c,AbpUsers d,TypeNumberInfo e where a.Id=b.LoadCarId and a.CarInfoId=c.Id and a.DriverUserId=d.Id and b.TypeNumberInfoId =e.Id order by a.CreationTime desc";
            //var listmodel = _sqlExecuter.FromDapperSqlQuery<LoadCarDetailsDto>(sql, null).AsQueryable();
            #endregion

            var usermodel = await _userManager.FindByIdAsync(AbpSession.UserId.Value.ToString());
            var listmodel = _repositoryLoadCar.GetAllIncluding(o => o.CarInfoModel).Where(o => o.CarInfoModel.FactoryinfoId == usermodel.FactoryinfoId).Join(_repositoryUser.GetAll(), a => a.DriverUserId, b => b.Id, (a, b) => new
            {
                a.Id,
                a.CreationNumber,
                a.ExamineStatus,
                a.CreationTime,
                a.DriverUserId,
                b.Name,
                a.CarInfoModel.PlatesNumber,
                a.CarStatus
            }).Join(_repositoryLoadingCarInfo.GetAllIncluding(o => o.TypeNumberInfoModel), a => a.Id, b => b.LoadCarId, (a, b) => new LoadCarDetailsDto
            {
                CreationNumber = a.CreationNumber,
                ExamineStatus = a.ExamineStatus,
                CreationTime = a.CreationTime,
                DriverUserId = a.DriverUserId.Value,
                DriverName = a.Name,
                PlatesNumber = a.PlatesNumber,
                CarStatus = a.CarStatus,
                TypeNumberName = b.TypeNumberName,
                Countproduct = b.Countproduct,
                Unit = b.TypeNumberInfoModel.Unit
            });

            if (filter.ExamineStatus.HasValue)
                listmodel = listmodel.Where(o => o.ExamineStatus == filter.ExamineStatus);

            if (filter.DriverId.HasValue)
                listmodel = listmodel.Where(o => o.DriverUserId == filter.DriverId);

            if (!string.IsNullOrEmpty(filter.PlatesNumber))
                listmodel = listmodel.Where(o => o.PlatesNumber.Contains(filter.PlatesNumber));

            if (filter.BeginLimit.HasValue)
                listmodel = listmodel.Where(o => o.CreationTime >= filter.BeginLimit);

            if (filter.EndLimit.HasValue)
                listmodel = listmodel.Where(o => o.CreationTime <= filter.EndLimit.Value.AddHours(24));

            var list = listmodel.GroupBy(o => o.CreationNumber);

            List<LoadCarExportDto> exportList = new List<LoadCarExportDto>();
            foreach (var item in list)
            {
                LoadCarExportDto dto = new LoadCarExportDto();
                if (item.Count() > 0)
                {
                    dto.CreationNumber = item.First().CreationNumber;
                    dto.ExamineStatus = item.First().ExamineStatus;
                    dto.CreationTime = item.First().CreationTime;
                    dto.DriverName = item.First().DriverName;
                    dto.PlatesNumber = item.First().PlatesNumber;
                    dto.CarStatus = item.First().CarStatus;
                    dto.loadCarDetailsList = new List<LoadCarDetailsModel>();
                    foreach (var temp in item)
                    {
                        LoadCarDetailsModel model = new LoadCarDetailsModel()
                        {
                            TypeNumberName = temp.TypeNumberName,
                            Countproduct = temp.Countproduct,
                            Unit = temp.Unit
                        };
                        dto.loadCarDetailsList.Add(model);
                    }
                }
                exportList.Add(dto);
            }
            return await exportList.ToListAsync();
        }
        public async Task<LoadCarOutputDto> GetLoadingInvoiceAsync(Guid id)
        {
            var user = await _userManager.FindByIdAsync(AbpSession.UserId.Value.ToString());
            var query = (await GetCache).AsQueryable().Where(o => o.CarInfoModel.FactoryinfoId == user.FactoryinfoId && o.Id == id).FirstOrDefault();

            var data = _map.Map<LoadCarOutputDto>(query);

            var delis = _distributionInfoRepository.GetAll().Where(o => o.LoadCarId == data.Id).Count();
            data.DeliveredCount = delis;

            data.DriverName = (await _userManager.FindByIdAsync(data.CarInfoModel.EmployeeCarUserId.ToString())).Name;

            return data;
        }

        public async Task<IPagedList<LoadCarDetailsOutputDto>> GetLoadDetailsAsync(int pageIdx, int pageSize, LoadDetailsFilter filter = null)
        {

            var model = GeLoadCarDetailsOutputDtoCache.AsQueryable();
            if (filter != null)
            {
                if (filter.ExamineStatus.HasValue)
                    model = model.Where(o => o.ExamineStatus == filter.ExamineStatus);

                if (filter.BeginLimit.HasValue)
                    model = model.Where(o => o.CreationTime >= filter.BeginLimit);

                if (filter.EndLimit.HasValue)
                    model = model.Where(o => o.CreationTime <= filter.EndLimit.Value.AddHours(24));

                if (filter.DriverId.HasValue)
                    model = model.Where(o => o.DriverUserId == filter.DriverId.Value);

                if (!string.IsNullOrWhiteSpace(filter.PlatesNumber))
                    model = model.Where(o => o.PlatesNumber.Contains(filter.PlatesNumber));
            }

            var list = await model.OrderByDescending(o => o.CreationTime).ToPagedListAsync(pageIdx, pageSize);
            foreach (var item in list)
            {
                var query = GetLodingDetailsDtoCache.Where(o => o.Id == item.Id);
                item.Lodings = GetLodingDetailsDtoCache.Where(o => o.Id == item.Id).ToList();
            }
            return list;
        }

        #endregion
        #region 后台缓存私有方法
        private List<LoadCarDetailsOutputDto> GeLoadCarDetailsOutputDtoCache
        {
            get
            {

                ICache cache = _catchmanager.GetCache(nameof(LoadCarDetailsOutputDto));
                return cache.Get("list", () => LoadCarDetailsOutputDtoCatch().ToList());
            }
        }
        private IQueryable<LoadCarDetailsOutputDto> LoadCarDetailsOutputDtoCatch()
        {
            var user = Task.Run(() => _userManager.GetUserByIdAsync(AbpSession.UserId.Value)).Result;
            string sql = string.Format($@"select * from dbo.V_loadCar where 1=1 and FactoryInfoId='{user.FactoryinfoId}'");
            return _sqlExecuter.FromSqlQuery<LoadCarDetailsOutputDto>(sql, null);
        }

        private List<LodingDetailsDto> GetLodingDetailsDtoCache
        {
            get
            {
                ICache cache = _catchmanager.GetCache(nameof(LodingDetailsDto));
                return cache.Get("list", () => LodingDetailsDtoCatch().ToList());
            }
        }

        private IQueryable<LodingDetailsDto> LodingDetailsDtoCatch()
        {

            var user = Task.Run(() => _userManager.GetUserByIdAsync(AbpSession.UserId.Value)).Result;
            string sql2 = string.Format($@"select * from  dbo.V_LoadInfoDetails where 1=1 ");
            return _sqlExecuter.FromSqlQuery<LodingDetailsDto>(sql2, null);
        }

        private Task<List<LoadCar>> GetCache
        {
            get
            {
                ICache cache = _catchmanager.GetCache(nameof(LoadCar));
                return cache.GetAsync("list", async () => await _repositoryLoadCar.GetAllIncluding(o => o.CarInfoModel, o => o.LoadingCarInfoList).OrderByDescending(m => m.CreationTime).ToListAsync());
            }
        }
        #endregion
    }
}
